import 'package:dio/dio.dart';
import 'package:get/get.dart' as getx;
import '../../routes/app_pages.dart';
import 'user_service.dart';

/// 基础网络服务类 - 单例模式
class BaseService {
  static const String baseUrl =
      //:
      // 'https://video.cloudwasu.cn:10443/media-server-web/miniapp';
      'https://videox.wasu.cn:16060/media-server-web/miniapp';
  // 'https://videox.wasu.cn:16060/media-server-web/miniapp';

  static BaseService? _instance;
  late final Dio _dio;

  /// 用户token
  String? _token;

  /// 租户ID
  String? _tenantId;

  /// 是否正在处理登录过期（避免重复跳转）
  static bool _isHandlingLoginExpired = false;

  /// 单例工厂构造函数
  factory BaseService() {
    _instance ??= BaseService._internal();
    return _instance!;
  }

  /// 私有构造函数
  BaseService._internal() {
    _dio = Dio();
    _initDio();
  }

  /// 初始化Dio配置
  void _initDio() {
    _dio.options = BaseOptions(
      baseUrl: baseUrl,
      connectTimeout: const Duration(seconds: 30),
      receiveTimeout: const Duration(seconds: 30),
      sendTimeout: const Duration(seconds: 30),
      headers: {
        'Content-Type': 'application/json',
        'Accept': 'application/json',
      },
    );

    // 请求拦截器
    _dio.interceptors.add(
      InterceptorsWrapper(
        onRequest: (options, handler) {
          // 添加通用请求头
          if (_token != null) {
            options.headers['Authorization'] = _token;
          }
          if (_tenantId != null) {
            options.headers['x-tenant-id'] = _tenantId;
          }

          print('请求: ${options.method} ${options.path}');
          print('请求头: ${options.headers}');
          if (options.data != null) {
            print('请求数据: ${options.data}');
          }

          handler.next(options);
        },
        onResponse: (response, handler) {
          print('响应: ${response.statusCode} ${response.data}');
          handler.next(response);
        },
        onError: (error, handler) {
          print('网络错误: ${error.message}');
          _handleError(error);
          handler.next(error);
        },
      ),
    );
  }

  /// 设置认证信息
  void setAuth(String? token, String? tenantId) {
    _token = token;
    _tenantId = tenantId;
    print('BaseService已设置认证信息');
  }

  /// 检查是否有认证信息
  bool get hasAuth => _token != null && _tenantId != null;

  /// 清除认证信息
  void clearAuth() {
    _token = null;
    _tenantId = null;
  }

  /// GET请求
  Future<Response<T>> get<T>(
    String path, {
    Object? data,
    Map<String, dynamic>? queryParameters,
    Options? options,
  }) {
    return _dio.get<T>(
      path,
      data: data,
      queryParameters: queryParameters,
      options: options,
    );
  }

  /// POST请求
  Future<Response<T>> post<T>(
    String path, {
    Object? data,
    Map<String, dynamic>? queryParameters,
    Options? options,
  }) {
    return _dio.post<T>(
      path,
      data: data,
      queryParameters: queryParameters,
      options: options,
    );
  }

  /// PUT请求
  Future<Response<T>> put<T>(
    String path, {
    Object? data,
    Map<String, dynamic>? queryParameters,
    Options? options,
  }) {
    return _dio.put<T>(
      path,
      data: data,
      queryParameters: queryParameters,
      options: options,
    );
  }

  /// DELETE请求
  Future<Response<T>> delete<T>(
    String path, {
    Object? data,
    Map<String, dynamic>? queryParameters,
    Options? options,
  }) {
    return _dio.delete<T>(
      path,
      data: data,
      queryParameters: queryParameters,
      options: options,
    );
  }

  /// 错误处理
  void _handleError(DioException error) {
    String message = '网络环境不佳，请稍后尝试';

    switch (error.type) {
      case DioExceptionType.connectionTimeout:
      case DioExceptionType.sendTimeout:
      case DioExceptionType.receiveTimeout:
        message = '网络环境不佳，请稍后尝试';
        break;
      case DioExceptionType.badResponse:
        if (error.response?.statusCode == 401) {
          message = '登录已过期，请重新登录';
          _handleLoginExpired();
        } else {
          message = '网络环境不佳，请稍后尝试';
        }
        break;
      case DioExceptionType.cancel:
        message = '请求已取消';
        break;
      case DioExceptionType.unknown:
      default:
        message = '网络环境不佳，请稍后尝试';
        break;
    }

    // 不要显示错误信息给用户，按照用户要求
    print('网络错误详情: $message');
  }

  /// 处理登录过期逻辑
  void _handleLoginExpired() {
    // 如果已经在处理登录过期，避免重复处理
    if (_isHandlingLoginExpired) {
      return;
    }

    _isHandlingLoginExpired = true;

    try {
      // 调用UserService的统一登出处理方法
      final userService = getx.Get.find<UserService>();
      userService.handleLogout(callLogoutApi: false); // 401错误不需要再调用登出API

      print('登录已过期，已通过统一方法处理');
    } catch (e) {
      print('处理登录过期错误: $e');
      // 如果统一方法失败，回退到简单处理
      try {
        clearAuth();
        getx.Get.offAllNamed(Routes.LOGIN);
      } catch (fallbackError) {
        print('回退处理也失败: $fallbackError');
      }
    } finally {
      // 延迟重置标志，避免快速重复请求
      Future.delayed(const Duration(seconds: 2), () {
        _isHandlingLoginExpired = false;
      });
    }
  }
}
